<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on"
             label-position="left">

      <div class="title-container">
        <h3 class="title">管理员登录</h3>
      </div>

      <el-form-item prop="userName">
        <span class="svg-container">
          <svg-icon icon-class="phone"/>
        </span>
        <el-input
            ref="userName"
            v-model="loginForm.userName"
            placeholder="手机号"
            name="userName"
            type="text"
            tabindex="1"
            auto-complete="on"
        />
      </el-form-item>
      <el-form-item prop="code">
        <el-input style="width:300px;" v-model="loginForm.code"  maxlength="4"
                  show-word-limit placeholder="验证码"/>
        <el-button type="primary" style="width:140px;" :disabled="sending" @click="getCodeFun">{{ codeTest }}
        </el-button>
      </el-form-item>
      <el-form-item prop="userPass">
        <span class="svg-container">
          <svg-icon icon-class="userPass"/>
        </span>
        <el-input
            :key="userPassType"
            ref="userPass"
            v-model="loginForm.userPass"
            :type="userPassType"
            placeholder="userPass"
            name="userPass"
            tabindex="2"
            auto-complete="on"
            @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="userPassType === 'userPass' ? 'eye' : 'eye-open'"/>
        </span>
      </el-form-item>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;"
                 @click.native.prevent="handleLogin">登录
      </el-button>


    </el-form>
  </div>
</template>

<script>


export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        userName: '13055689976',
        userPass: '123456',
        code:''
      },
      loginRules: {
        userName: [{required: true, trigger: 'blur', message: '请填写手机号!'},
        {pattern: /^1[3456789]\d{9}$/, message: "手机号格式不对", trigger: "blur"},],
        userPass: [{required: true, trigger: 'blur', message: '请填写密码!'}],
        code: [{required: true, trigger: 'blur', message: '请填写验证码!'}]
      },
      code: '',//验证码
      loading: false,
      userPassType: 'userPass',
      redirect: undefined,
      sending: false, //是否发送验证码
      second: 120, //倒计时间
      codeTest: '获取验证码',
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.userPassType === 'userPass') {
        this.userPassType = ''
      } else {
        this.userPassType = 'userPass'
      }
      this.$nextTick(() => {
        this.$refs.userPass.focus()
      })
    },
    //用户登录
    handleLogin() {
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          this.loading = true
          let result = await this.$http.user.reqLogin(this.loginForm, this.loginForm.code)
          if (result.code !== 200) return this.$message.error(result.message)
          this.$message.success(`登录成功!欢迎您管理员${result.data.user.userName},您的上次登录时间${this.dateFormat(result.data.user.loginDate)}`)
          window.localStorage.setItem('user',JSON.stringify(result.data.user))
          this.$router.push('/dashboard')
          this.loading = false
        } else {
          this.loading = false
          this.$message.error("请填写完整且正确的用户信息")

        }
      })
    },
    getCodeFun() {

      this.$refs.loginForm.validateField("userName", async errMsg => {
        if (errMsg) {
         this.$message.error("请填写正确的手机号")
        } else {
         let result = await this.$http.user.reqSendMessage(this.loginForm.userName)
          if(result.code !== 200) return this.$message.error("验证码发送失败!")
          this.$message.success("验证码已发送,请尽快填写!")
          this.sending = true
          this.timeDown()
        }
      });
    },
    timeDown() {
      let result = setInterval(() => {
        --this.second;
        this.codeTest = this.second
        if (this.second < 2) {
          clearInterval(result);
          this.sending = false;
          this.disabled = false;
          this.second = 120;
          this.codeTest = "获取验证码"
        }
      }, 1000);
    },
    //时间格式化函数，此处仅针对yyyy-MM-dd hh:mm:ss 的格式进行格式化
    dateFormat(time) {
      let date=new Date(time);
      let year=date.getFullYear();
      /* 在日期格式中，月份是从0开始的，因此要加0
       * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
       * */
      let month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
      let day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
      let hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
      let minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
      let seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
      // 拼接
      return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
    }
  },

}
</script>

<style lang="scss">

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  background: url('~@/assets/images/88341058_p0.png');
  background-size: cover;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
